package com.chrisevansdev.irisysaudit;

import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import uk.co.irisys.StandardPacket;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NetworkClient extends Activity {

    private EditText serverIp, serverPort, clientDebug;
    @SuppressWarnings("unused")
	private Button btnSendPing, btnSendGetTime, btnSendEvent;
    private String strServerIp;
    private int nServerPort = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.network_client);

        serverIp = (EditText) findViewById(R.id.server_ip);
        serverPort = (EditText) findViewById(R.id.server_port);
        btnSendPing = (Button) findViewById(R.id.btnSendPing);
        btnSendGetTime = (Button) findViewById(R.id.btnSendGetTime);
        btnSendEvent = (Button) findViewById(R.id.btnSendEvent);
        clientDebug = (EditText) findViewById(R.id.client_debug);
        
    }


	// main onClick listener for activity
    public void onClick(View view) 
    {
	  	strServerIp = serverIp.getText().toString();
		nServerPort = Integer.parseInt(serverPort.getText().toString());
				
		switch (view.getId()) {
		
		case R.id.btnSendPing:
			
			break;
			
		case R.id.btnSendGetTime:
			
			break;
			
		case R.id.btnSendEvent:
			
			break;
		
		default:
			break;
		}
		
		if (!strServerIp.isEmpty() && nServerPort > 0) 
		{
			try {

				InetAddress serverAddr = InetAddress.getByName(strServerIp);

				clientDebug.setText("Connecting...");
									
				Socket socket = new Socket(serverAddr, nServerPort);

				try {
					
					StandardPacket pkt = StandardPacket.MakeObject();
					
					pkt.WriteByte(StandardPacket.ESC);
					pkt.WriteByte(StandardPacket.SOF);
												
					pkt.WriteByte((byte)1);
					pkt.WriteByte((byte)0);
					pkt.WriteByte((byte)0);
											
					pkt.WriteByte(StandardPacket.ESC);
					pkt.WriteByte(StandardPacket.EOF);
										
					OutputStream os = socket.getOutputStream();
					os.write(pkt.GetPacket());
											
					clientDebug.setText("Sent Ping");
														
				} catch (Exception e) {

					clientDebug.setText("Error Sending");
					
				} finally {

					socket.close();
				}
			} catch (Exception e) {

				clientDebug.setText("Error Getting Socket");
			}
		}
    }
}